import { workbenchesTabs } from "@/service/general/menu";
import { WorkbenchesTabProps } from "@/service/general/modal/MenuModal";
import React, { useEffect, useState } from "react";
import { AddSvg, DeleteSvg, EditSvg, MoreSvg, SearchSvg, SimpleAppSvg, TimeSvg } from "../assets/CustomizeSvg";
import { UtilHelpers } from "@/service/general/utils/utilHelpers";
import { message, Popover } from "antd";
import { ResponseModal } from "@/service/request/modal/responseModal";
import { ApplicationData } from "@/service/request/modal/dataModal";
import { useMainContentContext } from "@/service/general/publicStatic";
import { OperationType } from "@/service/general/enumType";
import { WorkbenchesDetail } from "./detail/WorkbenchesDetail";
import { isLoggedIn } from "@/service/axiosManager";
import { getSessionItem, setSessionItem } from "@/service/sessionStorageManager";

const WorkbenchesView = () => {
    const {to} = useMainContentContext();
    const [initData, setInitData] = useState<boolean>(false);
    const [tabs, setTabs] = useState<WorkbenchesTabProps[]>(workbenchesTabs);
    const [searchValue, setSearchValue] = useState<string>('');
    const [workbenchesDatas, setWorkbenchesDatas] = useState<ApplicationData[]>();
    const tabKey = "__APPLICATION_ACTIVE_TAB_KEY";


    useEffect(() => {
        Initialize();
    });

    const Initialize = () => {
        if (!initData && isLoggedIn()) {
            setInitData(true);
            const cacesTabs = getSessionItem(tabKey);
            if (cacesTabs) {
                const tabItem = workbenchesTabs.find(item => item.id === cacesTabs.id) || workbenchesTabs[0];
                switchTab({...tabItem});
            } else {
                switchTab(workbenchesTabs[0]);
            }
            // loadData();
            // ...
        }
    }

    const Dispose = () => {
        setWorkbenchesDatas(undefined);
    }

    const loadData = (item: WorkbenchesTabProps) => {
        // getApplicationList()
        item.get().then((res: ResponseModal<ApplicationData>) => {
            console.log(res);
            if (res.code === 0 && res.success) {
                const result = res.result;
                // setWorkbenchesDatas([...(result?.map((item) => {
                //     let datasetIds = item.datasetIds;
                //     if (!Array.isArray(item.datasetIds)) {
                //         datasetIds = item.datasetIds ? [item.datasetIds]:[];
                //     }
                //     return {...item, datasetIds: datasetIds};
                // }) ?? [])]);
                setWorkbenchesDatas(result);
            } else if (res.message && res.message.length > 0) {
                message.error(res.message);
            }
        }).catch((err) => {
            console.log("获取列表失败", err);
        });
    }

    const searchChang = (e: React.ChangeEvent<HTMLInputElement>) => {
        const changValue = e.currentTarget.value || e.target.value;
        setSearchValue(changValue);
    }

    const switchTab = (newItem: WorkbenchesTabProps) => {
        Dispose();
        setTabs(workbenchesTabs.map(item => ({
            ...item,
            isActive: item.id === newItem.id,
        })));
        loadData(newItem);
    }

    const getActiveTab = () => {
        return tabs.find(item => item.isActive) || tabs[0];
    }

    const toDetail = ({data, type}: {data?: ApplicationData,type: OperationType}) => {
        const detailView = <WorkbenchesDetail data={data} operationType={type} menuData={getActiveTab()}  />;
        setSessionItem(tabKey, {...getActiveTab()});
        to(detailView);
    }

    const deleteData = (item: ApplicationData) => {
        const param = {
            id: item.id
        }
        getActiveTab().delete(param).then((res: ResponseModal<boolean>) => {
            console.log("res: \n", res);
            if (res.code === 200 && res.success && res.result) {
                message.success("删除成功");
                loadData(getActiveTab());
            } else if (res.message && res.message.length > 0) {
                message.error(res.message);
            } else {
                message.error("删除失败，未知原因");
            }
        }).catch((err) => {
            console.log("删除失败: \n", err);
        });
    }

    return (<>
            <div className="w-full h-full py-3 text-black">
                <div className="w-full h-full flex flex-col items-start justify-start gap-5">
                    <div className="w-full flex flex-row items-center justify-between">
                        <div key={`workbenches_tab`} className="w-fit flex flex-row items-center justify-start gap-6">
                            {
                                tabs.map((item, index) => (
                                        <div key={`workbenches_tab_${item.id}_${index}`} className={`border-b-2 px-1 py-1 text-lg cursor-pointer ${item.isActive ? "text-blue-600 border-b-blue-500" : "text-gray-600 border-b-transparent"}`} onClick={() => {switchTab(item);}}>{item.name}</div>
                                ))
                            }
                        </div>
                        <div className="w-fit flex flex-row items-center justify-end gap-4">
                            <div className="w-fit h-full">
                                <div className="w-fit h-full flex flex-row items-center gap-2 justify-center border cursor-pointer border-gray-300 rounded-lg px-3 py-2 bg-white shadow-[0_0_5px_rgba(0,0,0,0)] shadow-transparent hover:border-blue-500 has-[input:focus-within]:border-blue-500 has-[input:focus-within]:shadow-blue-500">
                                    <div className="flex flex-row items-center justify-center"><SearchSvg /></div>
                                    <div className="w-52 h-full">
                                        <input type="text" value={searchValue} placeholder="搜索应用" className="w-full h-full border-none outline-none" onChange={searchChang} />
                                    </div>
                                </div>
                            </div>
                            <div>
                                <div className="flex flex-row items-center justify-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg cursor-pointer hover:bg-blue-600/90" onClick={() => {toDetail({type: OperationType.NEW})}}>
                                    <div className="w-[14px] flex flex-row items-center justify-center"><AddSvg width={`100%`} height={`100%`} /></div>
                                    <div className="">新建</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="w-full h-full overflow-y-auto">
                        <div className="grid grid-cols-4 gap-5">
                            {
                                workbenchesDatas && workbenchesDatas.length > 0 ? workbenchesDatas?.map((item,index) => (
                                    <>
                                        <div 
                                        key={`workbenches_card_${item.id}_${index}`} 
                                        className="group/card w-full h-fit flex flex-col items-center justify-center gap-2 border border-gray-200 shadow-md shadow-gray-200 bg-white rounded-lg p-4 cursor-pointer hover:border-blue-400 hover:shadow-transparent"
                                        onClick={() => {toDetail({data: item, type: OperationType.UPDATA})}}
                                        >
                                            <div className="w-full flex flex-row items-center justify-between">
                                                <div className="flex flex-row items-center justify-center gap-2">
                                                    <div className="w-fit p-1 bg-blue-300 rounded-md text-white flex flex-row items-center justify-center"><SimpleAppSvg /></div>
                                                    <div>{item.name}</div>
                                                </div>
                                                <div className="flex flex-row items-center justify-center gap-1 bg-gray-200 text-gray-500 -m-4 px-2 py-1 rounded-ss-md rounded-es-md text-xs">
                                                    <div className=""><SimpleAppSvg /></div>
                                                    <div>{getActiveTab().name}</div>
                                                </div>
                                            </div>
                                            <div className="w-full h-16 whitespace-pre-line break-words text-gray-500">
                                                {item.intro || "暂无简介"}
                                            </div>
                                            <div className="w-full flex flex-row items-center justify-between">
                                                <div className="flex flex-row items-center justify-center">
                                                    {/* <div className="flex flex-row items-center justify-center">
                                                        <LockOutlined className="w-4 mr-1" />
                                                    </div>
                                                    <div>私有</div> */}
                                                </div>
                                                <div className="w-fit text-gray-400">
                                                    <div className="group-hover/card:hidden flex flex-row items-center justify-center gap-2">
                                                        <div className="w-3 flex flex-row items-center justify-center"><TimeSvg width={`100%`} height={`100%`} /></div>
                                                        <div>{UtilHelpers.relativeTimeV2(item.createTime, 'MM-DD')}</div>
                                                    </div>
                                                    <Popover content={<>
                                                            <div className="flex flex-col items-center justify-center gap-2 p-2 rounded-lg border border-gray-100 cursor-pointer">
                                                                <div 
                                                                className="w-full flex flex-row items-center justify-center gap-2 px-3 py-1 hover:bg-gray-100 rounded-lg"
                                                                onClick={() => {toDetail({data: item, type: OperationType.UPDATA})}}
                                                                >
                                                                    <div className="w-4 flex flex-row items-center justify-center"><EditSvg width={`100%`} height={`100%`} /></div>
                                                                    <div>编辑信息</div>
                                                                </div>
                                                                <div className="w-full border-b border-b-gray-100"></div>
                                                                <div 
                                                                className="w-full flex flex-row items-center justify-start gap-2 px-3 py-1 text-red-600 hover:bg-red-100 rounded-lg" onClick={(event) => {event.stopPropagation();deleteData(item)}}
                                                                >
                                                                    <div className="w-4 flex flex-row items-center justify-center"><DeleteSvg width={`100%`} height={`100%`}/></div>
                                                                    <div>删除</div>
                                                                </div>
                                                            </div>
                                                        </>} 
                                                        arrow={false} 
                                                        trigger="hover" 
                                                        placement="bottomLeft"
                                                        overlayInnerStyle={{padding: 0,margin: 0}}
                                                        getPopupContainer={(node) => node}>
                                                    <div className="w-5 hidden group-hover/card:block flex-row items-center justify-center"><MoreSvg width={`100%`} height={`100%`} /></div>
                                                    </Popover>
                                                </div>
                                            </div>
                                        </div>
                                    </>
                                )): (<>
                                    <div>暂无数据</div>
                                </>)
                            }
                        </div>
                    </div>
                </div>
            </div>
        </>);
}

export {
    WorkbenchesView
}